package com.ktgj.train.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.FlightOrderChangeConstants;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.enums.TrainOrderEnum;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.CustomerCard;
import com.ktgj.customer.api.domain.DepositBusinessApi;
import com.ktgj.customer.api.domain.Employee;
import com.ktgj.customer.api.domain.FinanceOrderRefundment;
import com.ktgj.train.common.TrainTickets;
import com.ktgj.train.domain.*;
import com.ktgj.train.domain.InterfaceEntity.Tickets;
import com.ktgj.train.domain.InterfaceEntity.TrRetreatTicketRequest;
import com.ktgj.train.domain.InterfaceEntity.TrRetreatTicketResponse;
import com.ktgj.train.service.ITrainOrderService;
import com.ktgj.train.service.ITrainOrderitemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.train.mapper.TrainOrderRefundrecordMapper;
import com.ktgj.train.service.ITrainOrderRefundrecordService;

import javax.servlet.http.HttpServletRequest;

/**
 * 退票记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-11-29
 */
@Service
public class TrainOrderRefundrecordServiceImpl implements ITrainOrderRefundrecordService 
{
    @Autowired
    private TrainOrderRefundrecordMapper trainOrderRefundrecordMapper;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private ITrainOrderitemService trainOrderItemService;
    @Autowired
    private ITrainOrderService trainOrderService;
    @Autowired
    private TrainTickets trainTickets;

    /**
     * 查询退票记录
     * 
     * @param recordid 退票记录ID
     * @return 退票记录
     */
    @Override
    public TrainOrderRefundrecord selectTrainOrderRefundrecordById(Long recordid)
    {
        return trainOrderRefundrecordMapper.selectTrainOrderRefundrecordById(recordid);
    }

    @Override
    public List<TrainOrderRefundrecord> queryTrainOrderRefundrecord(String merchantOrderId) {
        return trainOrderRefundrecordMapper.queryTrainOrderRefundrecord(merchantOrderId);
    }

    /**
     * 查询退票记录列表
     * 
     * @param trainOrderRefundrecord 退票记录
     * @return 退票记录
     */
    @Override
    public List<TrainOrderRefundrecord> selectTrainOrderRefundrecordList(TrainOrderRefundrecord trainOrderRefundrecord)
    {
        return trainOrderRefundrecordMapper.selectTrainOrderRefundrecordList(trainOrderRefundrecord);
    }

    @Override
    public List<TrainOrderRefundrecord> queryTrainOrderRefundrecordList(Long orderId, String changeType) {
        return trainOrderRefundrecordMapper.queryTrainOrderRefundrecordList(orderId, changeType);
    }

    /**
     * 新增退票记录
     * 
     * @param trainOrderRefundrecord 退票记录
     * @return 结果
     */
    @Override
    public int insertTrainOrderRefundrecord(TrainOrderRefundrecord trainOrderRefundrecord)
    {
        return trainOrderRefundrecordMapper.insertTrainOrderRefundrecord(trainOrderRefundrecord);
    }

    /**
     * 修改退票记录
     * 
     * @param trainOrderRefundrecord 退票记录
     * @return 结果
     */
    @Override
    public int updateTrainOrderRefundrecord(TrainOrderRefundrecord trainOrderRefundrecord)
    {
        return trainOrderRefundrecordMapper.updateTrainOrderRefundrecord(trainOrderRefundrecord);
    }

    @Override
    public int updateByOrderItemId(TrainOrderRefundrecord trainOrderRefundrecord) {
        return trainOrderRefundrecordMapper.updateByOrderItemId(trainOrderRefundrecord);
    }

    /**
     * 修改退票记录（订单编号）
     *
     * @param trainOrderRefundrecord 退票记录
     * @return 结果
     */
    @Override
    public int updateByOrderId(TrainOrderRefundrecord trainOrderRefundrecord) {
        return trainOrderRefundrecordMapper.updateByOrderId(trainOrderRefundrecord);
    }

    /**
     * 批量删除退票记录
     * 
     * @param recordids 需要删除的退票记录ID
     * @return 结果
     */
    @Override
    public int deleteTrainOrderRefundrecordByIds(Long[] recordids)
    {
        return trainOrderRefundrecordMapper.deleteTrainOrderRefundrecordByIds(recordids);
    }

    /**
     * 删除退票记录信息
     * 
     * @param recordid 退票记录ID
     * @return 结果
     */
    @Override
    public int deleteTrainOrderRefundrecordById(Long recordid)
    {
        return trainOrderRefundrecordMapper.deleteTrainOrderRefundrecordById(recordid);
    }

    //查询改签记录列表
    @Override
    public List<TrainChangeOrderVO> queryTrainChangeOrderList(TrainCRMOrder order) {
        StringBuilder builder = new StringBuilder();
        if (order.getEndCreateTime() != null && order.getEndCreateTime() != "") {
            builder.append(order.getEndCreateTime());
            builder.append(" 23:59:59");
            order.setEndCreateTime(builder.toString());
        }
        if (order.getCustomerCard() != null && order.getCustomerCard() != "") {
            CustomerCard customerCard = remoteCustomerService.selectCustomerCard(order.getCustomerCard());
            order.setCustomerCard(String.valueOf(customerCard.getCustomerId()));
        }
        order.setChangeType(FlightOrderChangeConstants.change.getValue());
        List<TrainChangeOrderVO> changeOrderList = trainOrderRefundrecordMapper.queryTrainChangeOrderList(order);
        return changeOrderList;
    }

    //改签详情
    @Override
    public List<TrainChangeOrderVO> queryTrainChangeOrder(String orderId) {
        TrainCRMOrder order = new TrainCRMOrder();
        order.setOrderNumber(orderId);
        List<TrainChangeOrderVO> orderList = queryTrainChangeOrderList(order);
        orderList.forEach(item ->{
            TrainOrderitem orderitem = trainOrderItemService.selectTrainOrderitemById(Long.valueOf(item.getOrderitemid()));
            BeanUtils.copyProperties(orderitem, item);

            Map<String, Object> map = new HashMap<>();
            map.put("id", item.getId());
            Long aLong = remoteCustomerService.dominateIntegral(map);
            item.setDepositAmount(aLong);
        });
        return orderList;
    }

    //改签订单退票
    @Override
    public TrRetreatTicketResponse retreatTicket(HttpServletRequest servletRequest, TrRetreatTicketRequest request) throws Exception {
        TrainOrder trainOrder = trainOrderService.selectTrainOrderById(Long.valueOf(request.trainOrderId));

        BigDecimal amount = new BigDecimal(0);
        if (trainOrder.getDepositAmount() != null && trainOrder.getDepositAmount().compareTo(new BigDecimal(0)) > 0){
            amount = amount.add(trainOrder.getDepositAmount());
        }

        TrainOrderRefundrecord refundrecord = trainOrderRefundrecordMapper.amount(trainOrder.getOrderid());
        if (refundrecord != null){
            if (refundrecord.getAmount() != null && refundrecord.getAmount().compareTo(new BigDecimal(0)) > 0){
                amount = amount.add(refundrecord.getAmount());
            }
        }

        if (amount.compareTo(new BigDecimal(0)) > 0){
            DepositBusinessApi depositBusiness = new DepositBusinessApi();
            depositBusiness.setRemark("火车票改签退票" + trainOrder.getOrderid());
            depositBusiness.setState("false");
            depositBusiness.setBusinessType(EmHelper.businessType.TRAIN.getValue());

            String token = servletRequest.getHeader("token");
            Employee employee = remoteCustomerService.getLoginEmployeeByToken(token).getData();
            if (employee == null){
                throw new Exception("登录已过期");
            }

            depositBusiness.setOperatorId(employee.getEmployeeId());
            depositBusiness.setOrdersourceid(request.type);
            depositBusiness.setCustomerId(trainOrder.getJsjid());
            depositBusiness.setDetailamount(amount);
            depositBusiness.setChangetype(1l);
            depositBusiness.setLockState("true");
            depositBusiness.setOrderId(trainOrder.getOrderid());
            depositBusiness.setDrawState("true");
            Long aLong = remoteCustomerService.addReserveMoney(depositBusiness);
            if (aLong <= 0){
                throw new Exception("预留款记录添加失败");
            }
        }

        List<TrainOrderRefundrecord> refundrecords = trainOrderRefundrecordMapper.queryTrainOrderRefundrecordList(trainOrder.getOrderid(), FlightOrderChangeConstants.change.getValue());
        request.orderid = refundrecords.get(0).getMerchantOrderId();
        request.ordernumber = trainOrder.getOrder12306number();
        request.reqtoken = refundrecords.get(0).getReqToken();
        request.transactionid = trainOrder.getOrderpartnernumber();
        request.recordid.forEach(items -> {
            refundrecords.forEach(item -> {
                if (items.equals(String.valueOf(item.getRecordid()))) {
                    TrainOrderitem trainOrderitem = trainOrderItemService.selectTrainOrderitemById(item.getOrderitemid());
                    Tickets ticket = new Tickets();
                    ticket.passengername = trainOrderitem.getGuestname();
                    if (trainOrderitem.getIdtype().equals("ID_CARD")) {
                        ticket.passporttypeseid = "1";
                    } else if (trainOrderitem.getIdtype().equals("RPFHKMATR")) {
                        ticket.passporttypeseid = "2";
                    } else if (trainOrderitem.getIdtype().equals("MTPFHKAMR")) {
                        ticket.passporttypeseid = "C";
                    } else if (trainOrderitem.getIdtype().equals("MTPFTR")) {
                        ticket.passporttypeseid = "G";
                    } else if (trainOrderitem.getIdtype().equals("PASSPORT")) {
                        ticket.passporttypeseid = "B";
                    } else if (trainOrderitem.getIdtype().equals("PRICFF")) {
                        ticket.passporttypeseid = "H";
                    }
                    ticket.passportseno = trainOrderitem.getIdnumber();
                    ticket.ticket_no = item.getTicketNumber();
                    request.tickets.add(ticket);
                    item.setStatus(TrainOrderEnum.processing.getValue());
                    item.setOrderStatus(TrainOrderEnum.processing.getValue());
                    trainOrderRefundrecordMapper.updateTrainOrderRefundrecord(item);

                    FinanceOrderRefundment refundment = new FinanceOrderRefundment();
                    refundment.setOrderTypeId(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.train.getValue()));
                    refundment.setCustomerId(trainOrder.getJsjid());
                    refundment.setRefundmentType(Long.valueOf(com.ktgj.common.core.constant.FinanceOrderRefundment.originalRoad.getValue()));
                    refundment.setRefundmentAmount(trainOrder.getPayamount().add(new BigDecimal(item.getDifferencePrice()))); //TODO 测试，手续费暂为0，后期完善
                    refundment.setStatus(com.ktgj.common.core.constant.FinanceOrderRefundment.initial.toString());
                    refundment.setOrderId(String.valueOf(item.getOrderid()));
                    refundment.setApplyTime(new Date());
                    if (item.getPayType() != null){
                        if (item.getPayType().equals(BusinessTypeConstants.BankCredit.getValue())) {
                            refundment.setPaymentTypeId("2");
                        } else if (item.getPayType().equals(BusinessTypeConstants.BankDebit.getValue())) {
                            refundment.setPaymentTypeId("1");
                        }
                    }
                    refundment.setSerialnumber(item.getBillNo());
                    remoteCustomerService.add(refundment);
                }
            });
        });

        TrRetreatTicketResponse response = trainTickets.retreatTicket(request);
        return response;
    }
}
